﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;

namespace CCPSIP.iBeacon
{
    /// <summary>更新iBeacon的電量</summary>

    public class update_battery_life : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string[] Major = req.Form["Major"].Split(',');
                string[] Minor = req.Form["Minor"].Split(',');
                string[] BatteryLifeTemp = req.Form["BatteryLife"].Split(',');

                //【02】驗證Major, Minor, BatteryLife數目是否相等
                if (Major.Length != Minor.Length || Major.Length != BatteryLifeTemp.Length)
                    throw new Exception("Error01: The count of major, minor and battery life does not match."); //Major和Minor數目不相等

                //【03】驗證iBeacon是否存在
                for (int i = 0; i < Major.Length; i++)
                {
                    if (!iBeaconKit.IsBeaconExist(Major[i], Minor[i]))
                        throw new Exception("ERROR_02: iBeacon does not exist or not activate, major = " + Major[i] + " minor = " + Minor[i]); //此iBeacon不存在資料庫中或未啟用
                }

                //【04】BatteryLife轉型, 驗證值是否在0~100之間
                int[] BatteryLife = new int[BatteryLifeTemp.Length];
                for (int i = 0; i < BatteryLifeTemp.Length; i++)
                {
                    BatteryLife[i] = Convert.ToInt32(BatteryLifeTemp[i]);
                    if (BatteryLife[i] < 0 || BatteryLife[i] > 100)
                        throw new Exception("ERROR_03: The battery life value is out of range(0 ~ 100).");
                }

                //【05】驗證使用者身分
                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                    throw new Exception("ERROR_04: Cannot identify this device."); //無法識別此裝置

                //【06】若目前資料庫中的電量和傳入的新電量不同, 則更新資料庫中的電量
                List<ReturnStatus> ReturnStatus = new List<ReturnStatus>();
                for (int j = 0; j < Major.Length; j++)
                {
                    int BatteryLifeNow = iBeaconKit.GetBatteryLife(Major[j], Minor[j]);
                    bool IsUpdate = false;
                    if (BatteryLifeNow != BatteryLife[j])
                    {
                        iBeaconKit.UpdateBatteryLife(Major[j], Minor[j], BatteryLife[j]);
                        IsUpdate = true;
                    }

                    ReturnStatus.Add(new ReturnStatus(Major[j], Minor[j], BatteryLifeNow, BatteryLife[j], IsUpdate));
                }

                //【98】序列化ReturnStatus物件
                JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
                resultStr = JsonSerializer.Serialize(ReturnStatus);

                //【99】回傳Json
                context.Response.ContentType = "application/json";
                context.Response.Charset = null;
                context.Response.Write(resultStr);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
                //【99】回傳Xml
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
                context.Response.Charset = null;
                context.Response.Write(resultStr);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}